package com.group.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.group.login.LoginHandler;

@WebServlet("/ControllerServlet")
public class ControllerServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			processRequest(request,response);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	//	1단계, HTTP 요청 받음
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request,response);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws Throwable {
		//	2단계 요청분석
		String command = request.getParameter("cmd");
		CommandHandler handler = null;
		if(command == null){
			//	명령어 오류 처리
//			handler = new NullHandler();
		}else if(command.equals("Login")){
			handler = new LoginHandler();
		}
//		}else if(command.equals("BoardList")){
//			handler = new BoardListHandler();
//		}else if(command.equals("BoardWriteForm")){
//			handler = new BoardWriteFormHandler();
//		}
		//	3단계, 모델을 사용하여 요청한 기능을 수행한다.
		//	4단계, request나 session에 처리 결과를 저장
		HttpSession session = request.getSession();
		session.setAttribute("id", request.getParameter("id"));
		//	5단계, RequestDispatcher를 사용하여 알맞은 뷰에 포워딩
		String viewPage = handler.process(request,response);
//		System.out.println(viewPage);
		response.sendRedirect(viewPage);
//		RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher(viewPage);
//		dispatcher.forward(request, response);
	}

}
